//
//  MPBindPhoneContoller.m
//  MarkPlatform
//
//  Created by xiao6 on 2017/12/30.
//  Copyright © 2017年 AT. All rights reserved.
//

#import "MPBindPhoneContoller.h"
#import "ATLoginPhoneCell.h"
#import "ATLoginSmsCell.h"
#import "MPAppButton.h"
#import "BaseWebController.h"

@interface MPBindPhoneContoller ()
{
    UITextField *_phoneTextField;
    UITextField *_smsCodeTextField;
}
@property (nonatomic, strong) MPAppButton *bottomBtn;

@end

@implementation MPBindPhoneContoller
+ (instancetype)vcWithUserId:(NSString *)userId isEnterprise:(BOOL)isEnterprise {
    MPBindPhoneContoller *vc = [[self alloc] init];
    vc.userId = userId;
    vc.isEnterprise = isEnterprise;
    return vc;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self showNavTitle:self.userId ? @"绑定手机号" : @"手机验证码登录" backItem:YES];
    [self setupViews];
}

#pragma mark - actions
- (void)didClickTermsBtn:(id)sender {
    [self.navigationController pushViewController:[BaseWebController vcWithURLString:[[NSBundle mainBundle] URLForResource:@"TermsOfUse.html" withExtension:nil].absoluteString] animated:YES];
}
- (void)didClickPrivacyBtn:(id)sender {
    [self.navigationController pushViewController:[BaseWebController vcWithURLString:[[NSBundle mainBundle] URLForResource:@"PrivacyPolicy.html" withExtension:nil].absoluteString] animated:YES];
}
- (void)getSmsCode:(ATLoginSmsCell *)cell {
    // 结束编辑
    [self.view endEditing:YES];
    // 校验用户输入
    if (_phoneTextField.text.length < 11) {
        [MBProgressHUD showMessage:@"请输入正确的手机号码"];
        [_phoneTextField becomeFirstResponder];
        return;
    }
    // 获取验证码
    [MBProgressHUD showToView:self.view completion:^(MBProgressHUD *hud) {
        [MPHttpTool POST:[NSString stringWithFormat:@"business/getcode/%@", _phoneTextField.text]
                  params:nil
                 success:^(NSURLSessionDataTask *task, ATApiResult *result) {
                     [cell setGetSMSCodeDelay];
                     [hud hideWithMessage:@"验证码发送成功" completion:^{
                         [_smsCodeTextField becomeFirstResponder];
                     }];
                 } failure:^(NSString *errorMsg) {
                     [hud hideWithMessage:errorMsg completion:^{
                         [_smsCodeTextField  becomeFirstResponder];
                     }];
                 }];
    }];
}

- (void)didClickBottomBtn:(id)sender {
    // 结束编辑
    [self.view endEditing:YES];
    // 校验用户输入
    if (_phoneTextField.text.length < 11) {
        [MBProgressHUD showMessage:@"请输入正确的手机号码"];
        [_phoneTextField becomeFirstResponder];
        return;
    }
    if (_smsCodeTextField.text.length < 4) {
        [MBProgressHUD showMessage:@"请输入正确的验证码"];
        [_smsCodeTextField becomeFirstResponder];
        return;
    }
    // 注册
    [MBProgressHUD showToView:self.view completion:^(MBProgressHUD *hud) {
        if (self.userId) {
            [MPHttpTool POST:@"business/verifyCode"
                      params:@{@"userId" : SafeDicObj(self.userId),
                               @"code" : SafeDicObj(_smsCodeTextField.text),
                               @"tel" : SafeDicObj(_phoneTextField.text),
                               }
                     success:^(NSURLSessionDataTask *task, ATApiResult *result) {
                         ATUserModel *user = [ATUserModel modelWithJSON:result.data];
                         if (user.isLogin) {
                             [ATLocal loginWithUser:user];
                             [ATLocal setIsEnterprise:self.isEnterprise];
                             [hud hideWithSuccess:@"登录成功" completion:^{
                                 [self dismissOrPopToRootControlelr];
                             }];
                             return;
                         }
                         else {
                             [hud hideWithMessage:@"登录失败, 请重新登录" completion:^{
                                 [self goBack];
                             }];
                         }
                     } failure:ATHttpFailureWithHud(hud)];
        }
        else {
            [MPHttpTool POST:[NSString stringWithFormat:@"business/wxLogin1/%@", _phoneTextField.text] params:nil success:^(NSURLSessionDataTask *task, ATApiResult *result) {
                [hud hideWithSuccess:@"登录成功" completion:^{
                    ATUserModel *user = [ATUserModel modelWithJSON:result.data];
                    if (user.isLogin) {
                        [ATLocal loginWithUser:user];
                        [ATLocal setIsEnterprise:self.isEnterprise];
                        [self dismissOrPopToRootControlelr];
                        return;
                    }
                    [self.navigationController pushViewController:[MPBindPhoneContoller vcWithUserId:user.userId isEnterprise:self.isEnterprise] animated:YES];
                }];
            } failure:ATHttpFailureWithHud(hud)];
        }
    }];
}

#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 66;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        ATLoginPhoneCell *cell = [ATLoginPhoneCell cellForTableView:tableView indexPath:indexPath];
        cell.textFiled.text = _phoneTextField.text;
        _phoneTextField = cell.textFiled;
        [cell.textFiled notifyChange:^NSInteger(UITextField *textField, NSString *text) {
            return 11;
        }];
        return cell;
    }
    else {
        ATLoginSmsCell *cell = [ATLoginSmsCell cellForTableView:tableView indexPath:indexPath];
        cell.textFiled.text = _smsCodeTextField.text;
        _smsCodeTextField = cell.textFiled;
        [cell.textFiled notifyChange:^NSInteger(UITextField *textField, NSString *text) {
            return 4;
        }];
        __weak typeof(self) weakSelf = self;
        [cell setDidClickButton:^(ATLoginSmsCell *cell) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf getSmsCode:cell];
        }];
        return cell;
    }
}

#pragma mark - setupView
- (void)setupViews {
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 400)];
    [footer addSubview:self.bottomBtn];
    [self.bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bottomBtn.superview.mas_left).offset(16);
        make.centerX.equalTo(self.bottomBtn.superview);
        make.top.equalTo(self.bottomBtn.superview).offset(60);
        make.height.equalTo(@(SCALEW(49.0f)));
    }];
    
    self.tableView.tableFooterView = footer;
}

#pragma mark - getter
- (UIButton *)bottomBtn {
    if (!_bottomBtn) {
        _bottomBtn = [MPAppButton buttonWithTitle:self.userId ? @"绑定手机号" : @"登录" target:self action:@selector(didClickBottomBtn:)];
    }
    return _bottomBtn;
}
@end
